import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { viteMockServe } from 'vite-plugin-mock'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import Icons from 'unplugin-icons/vite'
import legacy from '@vitejs/plugin-legacy'

export default defineConfig(({ command }) => {
  const prodMock = true
  return {
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src') // 🌟 改用对象格式
      }
    },
    base: '/',
    server: {
      port: 3000,
      // proxy: {
      //   '/api': {
      //     target: 'http://localhost:3000',
      //     changeOrigin: true
      //   }
      // }
    },
    build: {
      outDir: 'dist',
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/[name].[hash].js',
          entryFileNames: 'assets/[name].[hash].js'
        }
      }
    },
    plugins: [
      vue(),
      viteMockServe({
        mockPath: 'mock',
        localEnabled: command === 'serve',
        prodEnabled: command !== 'serve' && prodMock,
        injectCode: `
          import { setupProdMockServer } from './mockProdServer'
          setupProdMockServer()
        `,
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
        imports: ['vue', 'vue-router'] // 🌟 显式声明自动导入
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      vueSetupExtend(),
      Icons({ autoInstall: true }), // 🌟 启用图标自动安装
      legacy({
        targets: ['defaults', 'not IE 11'], // 排除 IE 11
        modernPolyfills: ['es.array.at'] // 按需注入现代 API 的 polyfill
      }),
    ]
  }
})